<!--
  数据源选择器组件
  用于在表单中选择数据源

  属性:
  - modelValue: 选中的数据源ID (v-model)
  - placeholder: 占位符文本
  - disabled: 是否禁用
  - clearable: 是否可清空
-->
<template>
  <el-select
    v-model="selectedSource"
    :placeholder="placeholder"
    :disabled="disabled"
    :clearable="clearable"
    class="source-select"
  >
    <el-option
      v-for="option in sourceOptions"
      :key="option.value"
      :label="option.label"
      :value="option.value"
    >
      <div class="source-option">
        <span>{{ option.label }}</span>
        <el-tag size="small" :type="getSourceTypeTagType(getSourceType(option.value))">
          {{ getSourceTypeLabel(getSourceType(option.value)) }}
        </el-tag>
      </div>
    </el-option>
    <template #empty>
      <el-empty description="暂无数据源" :image-size="60" />
    </template>
  </el-select>
</template>

<script setup>
import { computed } from 'vue'
import { useDataSourceStore, dbTypeOptions } from '../../stores/dataSource'

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: null
  },
  placeholder: {
    type: String,
    default: '请选择数据源'
  },
  disabled: {
    type: Boolean,
    default: false
  },
  clearable: {
    type: Boolean,
    default: true
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'change'])

// 获取数据源 store
const dataSourceStore = useDataSourceStore()

// 预加载数据源
dataSourceStore.fetchSources()

// 计算属性：数据源选项
const sourceOptions = computed(() => dataSourceStore.sourceOptions)

// 计算属性：当前选中值
const selectedSource = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit('update:modelValue', val)
    emit('change', val)
  }
})

// 获取数据源类型
const getSourceType = (sourceId) => {
  const source = dataSourceStore.getSourceById(sourceId)
  return source ? source.type : null
}

// 获取数据源类型标签
const getSourceTypeLabel = (type) => {
  const option = dbTypeOptions.find(opt => opt.value === type)
  return option ? option.label : '未知'
}

// 获取数据源类型标签样式
const getSourceTypeTagType = (type) => {
  const typeMap = {
    mysql: 'success',
    postgresql: 'info',
    sqlserver: 'warning',
    oracle: 'danger'
  }
  return typeMap[type] || ''
}
</script>

<style scoped>
.source-select {
  width: 100%;
}

.source-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 5px;
}
</style>
